from django.shortcuts import render
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from datetime import date, timedelta
from rest_framework.generics import ListAPIView

from goods.models import CategoryVisitCount
from .home_serializers import CategoryVisitCountSerializer
from users.models import User
from orders.models import OrderInfo


# APIView一级视图 获取数据request.data  返回 Response(serializer.data)
# 用户总数
class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 过滤管理员用户
        count = User.objects.filter(is_staff=False).count()
        return Response({"count": count})


# 日增用户
class UserIncrementView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = User.objects.filter(date_joined__gte=date.today(), is_staff=False).count()
        return Response({"count": count})


# 日活动用户
class UserActiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = User.objects.filter(last_login__gte=date.today(), is_staff=False).count()
        return Response({"count": count})


# 日下单用户
class UserOrderView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = OrderInfo.objects.filter(create_time__gte=date.today()).count()
        return Response({"count": count})


# 月增用户
class UserMonthIncrement(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取30天以前的时间
        old_date = date.today() - timedelta(days=30)
        count_list = []
        for i in range(1, 31):
            # 获取当天时间
            current_date = old_date + timedelta(days=i)
            # 获取下一天时间
            next_date = old_date + timedelta(days=i + 1)
            count = User.objects.filter(date_joined__gte=current_date, date_joined__lt=next_date,
                                        is_staff=False).count()
            data_dict = {
                "count": count,
                "date": current_date
            }
            count_list.append(data_dict)
        return Response(count_list)


# 商品分类日访问量
class UserCategoryView(ListAPIView):  # 序列化全部对象
    pagination_class = None
    serializer_class = CategoryVisitCountSerializer
    queryset = CategoryVisitCount.objects.filter(date=date.today()).all()

# Create your views here.
